package com.daxia.bumall.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.daxia.bumall.daobase.GenericDAOHibernate;
import com.daxia.bumall.dto.ProductCategoryTagDTO;
import com.daxia.bumall.model.ProductCategory;
import com.daxia.bumall.model.ProductCategoryTag;
import com.daxia.bumall.support.Page;

@Repository
public class ProductCategoryTagDAO extends GenericDAOHibernate<ProductCategoryTag> {

    public List<ProductCategoryTag> find(ProductCategoryTagDTO dto, Page page) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From ProductCategoryTag n where 1 = 1 ");
        if (dto.getId() != null) {
            hql.append(" and n.id = ? ");
            paras.add(dto.getId());
        }
        if (dto.getProductCategory() != null) {
        	if (dto.getProductCategory().getId() != null) {
	            hql.append(" and n.productCategory.id = ? ");
	            paras.add(dto.getProductCategory().getId());
        	}
        }			
        if (StringUtils.isNotBlank(dto.getName())) {
            hql.append(" and n.name = ? ");
            paras.add(dto.getName());
        }		
        
        if (dto.getRelatedProductCategoryid() != null) {
        	hql.append(" and (n.productCategory.id = ? or n.productCategory.parentCategory.id = ? or n.productCategory.parentCategory.parentCategory.id = ?) ");
        	paras.add(dto.getRelatedProductCategoryid());
        	paras.add(dto.getRelatedProductCategoryid());
        	paras.add(dto.getRelatedProductCategoryid());
        }
        
        return super.find(hql.toString(), paras.toArray(), page);
    }
    
    public ProductCategoryTag findOne(ProductCategoryTagDTO dto) {
		Page page = new Page();
		page.setPageSize(1);
		page.setPage(1);
		
		List<ProductCategoryTag> list = this.find(dto, page);
	    return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

	public ProductCategoryTag findByProductCategoryAndName(Long productCategoryId, String tagName) {
		ProductCategoryTagDTO query = new ProductCategoryTagDTO();
		query.setProductCategory(new ProductCategory());
		query.getProductCategory().setId(productCategoryId);
		query.setName(tagName);
		return this.findOne(query);
	}
}
